package com.ysstech.activiti.service.impl;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ysstech.activiti.model.CommentEntity;
import com.ysstech.activiti.model.HistoryEntity;
import com.ysstech.activiti.service.ActivitiHistoryService;
import com.ysstech.common.entity.PageBean;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ActivitiHistoryServiceImpl implements ActivitiHistoryService {

    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;

    /**
     * 通过id查找用户发起的流程
     *
     * @param userId 发起人id
     * @return
     * @throws Exception
     */
    public Map<String, Object> queryFlow(String userId, PageBean page, String key) throws Exception {
        Map<String, Object> map = new HashMap<>();
        int pageNumber = Integer.parseInt(String.valueOf(page.getPageNum()));
        int pageSize = Integer.parseInt(String.valueOf(page.getPageSize()));
        List<HistoricProcessInstance> hisProInstance = null;
        Long count = null;
        if (true) {  //查询发起人对应的流程记录
            hisProInstance = historyService.createHistoricProcessInstanceQuery()
                    .startedBy(userId)
                    .listPage((pageNumber - 1) * pageSize, pageSize);
            count = historyService.createHistoricProcessInstanceQuery()
                    .startedBy(userId).count();
        } else { //我完成的流程
            hisProInstance = historyService.createHistoricProcessInstanceQuery()
                    .processDefinitionKey(key).involvedUser(userId).finished()
                    .orderByProcessInstanceEndTime().desc()
                    .listPage((pageNumber - 1) * pageSize, pageSize);
            count = historyService.createHistoricProcessInstanceQuery()
                    .processDefinitionKey(key).involvedUser(userId).finished().count();
        }
        map.put("rows", this.getHistoryEntity(hisProInstance));
        map.put("total", count);
        return map;
    }

    /**
     * 流程信息(包含审批信息)
     *
     * @param hisProInstance
     * @return
     */
    private List<HistoryEntity> getHistoryEntity(List<HistoricProcessInstance> hisProInstance) {
        List<HistoryEntity> historyEntityList = new ArrayList<>();
        for (HistoricProcessInstance hpi : hisProInstance) {
            HistoryEntity historyEntity = new HistoryEntity();
            historyEntity.setProcessDefinitionKey(hpi.getProcessDefinitionKey());
            historyEntity.setProcessDefinitionName(hpi.getProcessDefinitionName());
            historyEntity.setProcessDefinitionVersion(hpi.getProcessDefinitionVersion());
            historyEntity.setStartTime(hpi.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
            List<Comment> list = taskService.getProcessInstanceComments(hpi.getId()); //获取流程实例ID
            List<CommentEntity> commentEntityList = new ArrayList<>();
            for (Comment comment : list) { //审批信息
                CommentEntity commentEntity = new CommentEntity();
                commentEntity.setUserId(comment.getUserId());
                commentEntity.setDatetime(comment.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                commentEntity.setMsg(comment.getFullMessage());
                commentEntityList.add(commentEntity);
            }
            if (null == hpi.getEndTime()) {//流程还没有结束
                Task task = taskService.createTaskQuery().processInstanceId(hpi.getId()).orderByProcessDefinitionId().desc().singleResult();//最后一次的id
                if (null != task) {
                    historyEntity.setId(task.getId()); //正再执行的流程编号
                }
            } else {//流程结束
                historyEntity.setEndTime(hpi.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                historyEntity.setId(hpi.getId());//流程编号
            }
            //historyEntity.setId(hpi.getId());//获取流程实例ID
            historyEntity.setList(commentEntityList); //历史批注
            historyEntityList.add(historyEntity);
        }
        return historyEntityList;
    }

}
